package com.hyq.learn.ai.config;

import com.google.common.collect.Lists;
import com.hyq.learn.ai.filter.RequestResponseCachingFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author heyuqin
 * @date 2025/11/4 11:17
 */
@Configuration
public class FilterConfig {

    // 跨域问题处理
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfig());
        CorsFilter corsFilter = new CorsFilter(source);
        FilterRegistrationBean<CorsFilter> registration = new FilterRegistrationBean<>(corsFilter);
        registration.addUrlPatterns("/*");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        registration.setName("corsFilter");
        return registration;
    }

    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOriginPattern("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.setAllowedMethods(Lists.newArrayList("GET", "POST", "OPTIONS"));
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }

    @Bean
    public FilterRegistrationBean<RequestResponseCachingFilter> registerRequestCachingFilter() {
        FilterRegistrationBean<RequestResponseCachingFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new RequestResponseCachingFilter());
        registration.addUrlPatterns("/*");
        // 执行顺序（越小越先执行）
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        return registration;
    }

}
